const { DataTypes } = require('sequelize')
const { sequelize } = require('../config/database')

const AiConfig = sequelize.define('AiConfig', {
  id: {
    type: DataTypes.UUID,
    primaryKey: true,
    allowNull: false,
    defaultValue: DataTypes.UUIDV4
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    unique: true
  },
  provider: {
    type: DataTypes.STRING(50),
    allowNull: false
  },
  model: {
    type: DataTypes.STRING(100),
    allowNull: false
  },
  apiKey: {
    type: DataTypes.TEXT,
    allowNull: false
  },
  baseUrl: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  maxTokens: {
    type: DataTypes.INTEGER,
    allowNull: true,
    defaultValue: 4000
  },
  temperature: {
    type: DataTypes.DECIMAL(3, 2),
    allowNull: true,
    defaultValue: 0.7,
    validate: {
      min: 0,
      max: 2
    }
  },
  topP: {
    type: DataTypes.DECIMAL(3, 2),
    allowNull: true,
    defaultValue: 1.0,
    validate: {
      min: 0,
      max: 1
    }
  },
  frequencyPenalty: {
    type: DataTypes.DECIMAL(3, 2),
    allowNull: true,
    defaultValue: 0.0,
    validate: {
      min: -2,
      max: 2
    }
  },
  presencePenalty: {
    type: DataTypes.DECIMAL(3, 2),
    allowNull: true,
    defaultValue: 0.0,
    validate: {
      min: -2,
      max: 2
    }
  },
  systemPrompt: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  isActive: {
    type: DataTypes.BOOLEAN,
    defaultValue: true
  },
  isDefault: {
    type: DataTypes.BOOLEAN,
    defaultValue: false
  },
  settings: {
    type: DataTypes.JSON,
    allowNull: true
  },
  userId: {
    type: DataTypes.UUID,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  }
}, {
  tableName: 'ai_configs',
  timestamps: true,
  createdAt: 'createdAt',
  updatedAt: 'updatedAt',
  indexes: [
    {
      unique: true,
      fields: ['name']
    },
    {
      fields: ['provider']
    },
    {
      fields: ['isActive']
    },
    {
      fields: ['isDefault']
    }
  ]
})

module.exports = AiConfig